package com.jinhe.tss.component;

import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractTransactionalJUnit38SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;

import com.jinhe.tss.core.Global;
import com.jinhe.tss.core.cachepool.extend.connection.DBHelper;
import com.jinhe.tss.core.sso.DemoOperator;
import com.jinhe.tss.core.sso.IdentityCard;
import com.jinhe.tss.core.sso.TokenUtil;
import com.jinhe.tss.core.sso.context.Context;
import com.jinhe.tss.core.util.FileHelper;
import com.jinhe.tss.core.util.URLUtil;

@ContextConfiguration(
  locations={
    "classpath:spring/testComponentApplicationContext.xml",  
    "classpath:spring/component-applicationContext.xml",  
    "classpath:spring/core-applicationContext.xml"    
  }   
) 
@TransactionConfiguration(defaultRollback = true) // 自动回滚设置为false，否则数据将不插进去
public abstract class TxTestSupport extends AbstractTransactionalJUnit38SpringContextTests { 
 
    protected static Logger log = Logger.getLogger(TxTestSupport.class);    
    
    @Autowired protected IH2DBServer dbserver;
    
    protected void setUp() throws Exception {
        super.setUp();
        Global.setContext(super.applicationContext);
        
        if( !dbserver.isPrepareed() ) {
            String path = URLUtil.getResourceFileUrl("com/jinhe/tss").getPath();
            String sqlpath = path.substring(1, path.indexOf("jinhe-tss") + 9) + "/tss-webapp/sql/component";
            
            TxTestSupport.excuteSQL(sqlpath);
            dbserver.setPrepareed(true);
        }
        
        String token = TokenUtil.createToken(new Random().toString(), new Long(12)); 
        IdentityCard card = new IdentityCard(token, new DemoOperator(12L));
        Context.initIdentityInfo(card);
        
        HttpServletResponse response = new MockHttpServletResponse();
        Context.setResponse(response);
    }
 
    protected void tearDown() throws Exception {
        super.tearDown();
        dbserver.stopServer();
        
        FileHelper.renameFile("META-INF/persistence.xml", "persistence.xml_");
    }
    
    public static void excuteSQL(String sqlDir) {  
        log.info("正在执行目录：" + sqlDir+ "下的SQL脚本。。。。。。");  
        try {  
            Connection conn = DBHelper.getConnection();
            Statement stat = conn.createStatement();  
            
            List<File> sqlFiles = FileHelper.listFilesByTypeDeeply(".sql", new File(sqlDir));
            for(File sqlFile : sqlFiles) {
                stat.execute(FileHelper.readFile(sqlFile));
                log.info("SQL脚本：" + sqlFile+ " 执行完毕。");  
            }
 
            log.info("成功执行目录：" + sqlDir+ "下的SQL脚本!");
            
            stat.close();  
            conn.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
            throw new RuntimeException("目录：" + sqlDir+ "下的SQL脚本执行出错：", e);
        }
    }
}
